// lives/live/live.js
let comment_timer = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    rePlayCtx: null, // 回放播放器
    playerCtx: null, // 直播组件上下文
    live: null, // live对象
    room_id: null, // 直播间id
    loading: false,
    loadingLive: false,
    city: '',
    menuButton: null,
    muted: false, // 静音
    likeCount: 0, // 点赞数量
    inputFocus: true, // input获取焦点
    comment: '', // 当前评论内容
    commentBottomHeight: 0, // 评论框距离底部距离
    comments: [], // 评论列表
    scrollIntoView: '', // 评论列表滚动id
    isShowGoods: false,
    replaySrc: '', // 当前回放地址
    replayArr: [], // 回放视频列表
    initialTime: 0, // 回放视频播放位置
    showShareModal: false, // 显示分享菜单弹窗
    share_qrcode_active: false,
    share_qrcode: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var scene = decodeURIComponent(options.scene);
    scene && (scene = getApp().helper.scene_decode(scene));
    getApp().page.onLoad(this, options)
    if (scene.room_id) {
      options.room_id = scene.room_id
    }
    this.setData({
      room_id: options.room_id,
      menuButton: wx.getMenuButtonBoundingClientRect()
    })
    this.setData({
      playerCtx: wx.createLivePlayerContext('live-player')
    })
    //this.setFullScreen()
    this.getData(this.data.room_id)
    // this.getComment()
  },

  setFullScreen: function () {
    if (!this.data.playerCtx) {
      return
    }
    this.data.playerCtx.requestFullScreen({
      direction: 0,
      success: () => {
        // wx.showToast({
        //   title: '进入全屏',
        //   icon: 'none'
        // })
      },
      fail: () => {
        // wx.showToast({
        //   title: '全屏设置失败',
        //   icon: 'none'
        // })
      }
    })
  },

  getData: function (room_id) {
    wx.showLoading({
        title: '加载中...',
    });
    let is_look = wx.getStorageSync('live_room_look_' + room_id)
    getApp().request({
        url: getApp().api.live.get_live,
        data: {
          room_id: room_id,
          is_look: is_look ? true : false
        },
        success: res => {
            if (res.code == 0) {
              this.setData({
                loadingLive: true,
                loading: true,
                live: res.data
              })
              console.log(this.data.live)
              if ((this.data.live.record != null || this.data.live.record != '') && this.data.live.end_time > 0) {
                this.setData({
                  rePlayCtx: wx.createVideoContext('re-video')
                })
                if (this.rePlayCtx) {
                  this.rePlayCtx.requestFullScreen()
                }
                let replayArr = this.data.live.record
                this.setData({
                  replaySrc: replayArr.shift(),
                  replayArr: replayArr
                })
              } else {
                let user = getApp().getUser()
                getApp().request({
                  url: getApp().api.live.add_comment,
                  data: {
                    content: user.nickname + ' 进来了',
                    room_id: this.data.room_id,
                    type: 3
                  },
                  method: 'POST',
                  success: res => {
                  }
                })
                this.getComment()
                comment_timer = setInterval(() => {
                  this.getComment()
                }, 5000)
              }
              wx.setStorageSync('live_room_look_' + room_id, true)
            } else {
              wx.showModal({
                title: "提示",
                content: res.msg,
                showCancel: !1,
                confirmText: "确认",
                success: function (t) {
                  t.confirm && wx.navigateBack({
                    delta: 1
                  });
                }
              })
            }
        },
        complete: () => {
          wx.hideLoading();
        }
    })
  },

  /**
   * 回放视频如果有多个，自动切换下一个
   */
  onBindended: function () {
    if (this.data.replayArr.length > 0) {
      let replayArr = this.data.replayArr
      this.setData({
        replaySrc: replayArr.shift(),
        replayArr: replayArr,
        initialTime: 0
      })
    } else {
      wx.showToast({
        title: '播放完毕',
        icon: 'none'
      })
    }
  },

  /**
   * 播放变化事件 
   */
  onStatechChange: function (e) {
    console.log('监听状态变化', e.detail.code)
    if (e.detail.code == -2301) {
      console.log('直播已关闭')
      wx.showToast({
        title: '直播已结束'
      })
    }
  },

  /**
   * 网络变化事件
   */
  onNetStatus: function (e) {
  },

  /**
   * 点赞
   */
  onClickLike: function () {
    let cache_like = wx.getStorageSync('live_room_like_' + this.data.room_id)
    wx.setStorageSync('live_room_like_' + this.data.room_id, cache_like ? cache_like + 1 : 1)
    this.setData({
      likeCount: this.data.likeCount + 1
    })
  },

  /**
   * 点击评论
   */
  onClickComment: function () {
    this.setData({
      inputFocus: false
    })
  },

  /**
   * 点击设置
   */
  onClickSetting: function () {

  },

  /**
   * 点击商品图标
   */
  onClickGoods: function () {
    this.setData({
      isShowGoods: true
    })
  },

  /**
   * 关注
   */
  onFollow: function () {
    let that = this
    if (this.data.live.is_follow) {
      wx.showModal({
        title: "提示",
        content: '确定要取消关注吗?',
        showCancel: true,
        confirmText: "确认",
        success: function (t) {
          if (t.confirm) {
            wx.showLoading({
              title: '操作中...',
            });
            getApp().request({
              url: getApp().api.live.follow_status,
              data: {
                is_follow: 0,
                anchor_id: that.data.live.anchor_id
              },
              success: res => {
                if (res.code == 0) {
                  wx.showToast({
                    title: '取消关注成功',
                    icon: 'none',
                  })
                  let live = that.data.live
                  live.is_follow = 0
                  that.setData({
                    live: live
                  })
                }
              },
              complete: () => {
                wx.hideLoading();
              }
            })
          }
        }
      })
      return
    }
    wx.showLoading({
      title: '操作中...',
    });
    getApp().request({
      url: getApp().api.live.follow_status,
      data: {
        is_follow: 1,
        anchor_id: that.data.live.anchor_id
      },
      success: res => {
        if (res.code == 0) {
          wx.showToast({
            title: '关注成功',
            icon: 'none',
          })
          let live = that.data.live
          live.is_follow = 1
          this.setData({
            live: live
          })
        }
      },
      complete: () => {
        wx.hideLoading();
      }
    })
  },

  /**
   * 监听input输入
   */
  onCommentInput: function (e) {
    this.setData({
      comment: e.detail.value
    })
  },

  /**
   * 评论发送
   */
  onCommentConfirm: function (e) {
    if (this.data.comment.trim != '') {
      wx.showLoading({
        title: '发送中...',
      });
      getApp().request({
        url: getApp().api.live.add_comment,
        data: {
          content: this.data.comment.trim(),
          room_id: this.data.room_id
        },
        method: 'POST',
        success: res => {
          if (res.code == 0) {
            wx.showToast({
              title: '评论成功',
              icon: 'none',
            })
            this.getComment()
          } else {
            wx.showToast({
              title: '评论失败',
              icon: 'none',
            })
          }
        },
        complete: () => {
          wx.hideLoading();
        }
      })
    }
    this.setData({
      comment: '',
      commentBottomHeight: 0,
      inputFocus: true
    })
  },

  /**
   * 评论框获取键盘高度
   */
  onCommentFocus: function (e) {
    this.setData({
      commentBottomHeight: e.detail.height
    })
  },

  /**
   * 评论框失去焦点
   */
  onCommentBlur: function () {
    this.setData({
      commentBottomHeight: 0,
      inputFocus: true
    })
  },

  /**
   * 点击关闭goods弹窗
   */
  onClickCloseGoods: function () {
    this.setData({
      isShowGoods: false
    })
  },

  /**
   * 点击马上抢
   */
  onBuyGoods: function (e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goods/goods?id=' + id + '&live_room=' + this.data.room_id
    })
  },

  /**
   * 点击返回按钮
   */
  onClickBack: function () {
    if (getCurrentPages().length < 2) {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }else {
      wx.navigateBack({
        delta: 1
      })
    }
    
  },

  /**
   * 获取评论last_id
   */
  getCommentLastId: function () {
    if (this.data.comments.length > 0) {
      return this.data.comments[this.data.comments.length - 1].id
    }
    return 0
  },

  /**
   * 获取评论内容及点赞数量
   */
  getComment: function () {
    let cache_like = wx.getStorageSync('live_room_like_' + this.data.room_id)
    getApp().request({
      url: getApp().api.live.get_comment,
      data: {
        last_id: this.getCommentLastId(),
        like_count: cache_like ? cache_like : 0,
        room_id: this.data.room_id
      },
      success: res => {
        if (res.code == 0) {
          let live = this.data.live
          live.look_num = res.data.look_num
          this.setData({
            live: live,
            comments: this.data.comments.concat(res.data.list)
          })
          if (res.data.list.length > 0) {
            this.setData({
              scrollIntoView: 'comment-id-' + this.data.comments.length
            })
          }
          
          let new_like_count = res.data.like_count - (this.data.live.good_num + cache_like)
          wx.setStorageSync('live_room_like_' + this.data.room_id, 0)
          if (new_like_count > 0) {
            let timer = setInterval(() => {
              if (new_like_count <= 0) {
                clearInterval(timer)
              }
              new_like_count--
              let live = this.data.live
              live.good_num = live.good_num + 1
              this.setData({
                live: live
              })
            }, Math.random() * 1000)
          }
        }
      },
      complete: () => {
        // wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(comment_timer)
    this.getComment()
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  onClickSharePartner: function () {
    this.onClickShareClose()
  },
  onClickShare: function () {
    this.setData({
      showShareModal: true
    })
  },
  onClickShareClose: function () {
    this.setData({
      showShareModal: false
    })
  },
  onClickSharePoster: function () {
    this.onClickShareClose()
    this.setData({
      share_qrcode_active: 'active'
    })
    getApp().request({
      url: getApp().api.live.qrcode,
      data: {
        room_id: this.data.live.id
      },
      success: res => {
        if (res.code == 0) {
          this.setData({
            share_qrcode: res.data.pic_url
          })
        } else {
          this.setData({
            share_qrcode_active: ''
          })
          wx.showToast({
            title: '生成海报失败',
            icon: 'error',
            duration: 2000
          })
        }
      },
      complete: () => {}
    })
  },
  onShareQrcodeClose: function () {
    this.setData({
      share_qrcode_active: ''
    })
  },
  saveGoodsQrcode: function () {
    if (this.data.share_qrcode == '') {
      return
    }
    var e = this;
    getApp().core.saveImageToPhotosAlbum ? (getApp().core.showLoading({
      title: "正在保存图片",
      mask: !1
    }), getApp().core.downloadFile({
      url: e.data.share_qrcode,
      success: function (o) {
        getApp().core.showLoading({
          title: "正在保存图片",
          mask: !1
        }), getApp().core.saveImageToPhotosAlbum({
          filePath: o.tempFilePath,
          success: function () {
            getApp().core.showModal({
              title: "提示",
              content: "直播间海报保存成功",
              showCancel: !1
            });
          },
          fail: function (o) {
            getApp().core.showModal({
              title: "图片保存失败",
              content: o.errMsg,
              showCancel: !1
            });
          },
          complete: function (o) {
            getApp().core.hideLoading();
          }
        });
      },
      fail: function (o) {
        getApp().core.showModal({
          title: "图片下载失败",
          content: o.errMsg + ";" + e.data.share_qrcode,
          showCancel: !1
        });
      },
      complete: function (o) {
        getApp().core.hideLoading();
      }
    })) : getApp().core.showModal({
      title: "提示",
      content: "当前版本过低，无法使用该功能，请升级到最新版本后重试。",
      showCancel: !1
    });
  },
  shareQrcodeClick: function(o) {
    var e = o.currentTarget.dataset.src;
    getApp().core.previewImage({
        urls: [ e ]
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var user = getApp().getUser()
    return {
      path: '/lives/live/live?room_id=' + this.data.live.id + '&user_id=' + user.id + '&store_id=' + (wx.getStorageSync("store_id") ? wx.getStorageSync("store_id") : 1),
      title: this.data.live.desc,
      imageUrl: this.data.live.pic_url
    }
  }
})
